package com.dev.shiro.shiro;

import com.dev.shiro.entity.Login;
import com.dev.shiro.entity.UserOnline;
import com.dev.shiro.service.UserOnlineService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;

/**
 * @Classname MySessionListener
 * @Description TODO
 * @Date 2022/3/17 14:36
 * @Author niu hao
 */
public class MySessionListener implements SessionListener {

    @Resource
    private UserOnlineService userOnlineService;

    @Override
    public void onStart(Session session) {
        System.out.println("会话创建");
        Subject subject = SecurityUtils.getSubject();
        if (Objects.nonNull(subject)){

            UserOnline userOnline = new UserOnline();
            getUserOnline(session,userOnline);
            userOnline.setStatus(1);
            boolean save = userOnlineService.save(userOnline);
        }
    }

    @Override
    public void onStop(Session session) {
        System.out.println("会话停止");
        if (session == null){
            return;
        }
        userOnlineService.removeById(session.getId());
    }

    @Override
    public void onExpiration(Session session) {
        System.out.println("会话过期");
        if (session instanceof ValidatingSession && !((ValidatingSession)session).isValid()){
            return;
        }
        UserOnline userOnline = new UserOnline();
        getUserOnline(session,userOnline);
        userOnline.setStatus(0);
        userOnlineService.saveOrUpdate(userOnline);
    }

    private void getUserOnline(Session session,UserOnline userOnline) {
        Login login = (Login) SecurityUtils.getSubject().getPrincipal();
        userOnline.setSessionId(String.valueOf(session.getId()));
        userOnline.setSessionId(String.valueOf(session.getId()));
        userOnline.setLoginName(login.getLoginName());
        userOnline.setExpireTime((int) session.getTimeout());
        userOnline.setLastAccessTime(LocalDateTime.ofInstant(session.getLastAccessTime().toInstant(), ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))));
        userOnline.setLoginLocation(session.getHost());
    }
}
